package com.example.mydemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.example.mydemo.impl.MyFunction;
import com.example.mydemo.utils.CheckPermissionS;
import com.example.mydemo.utils.StorageUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SmsReceiver extends BroadcastReceiver {


    private MyFunction func_;
    //主页面上下文
    private Context context;

    public SmsReceiver(Context context) {
        this.context = context;
    }

    public SmsReceiver(Context context, MyFunction func) {
        this.context = context;
        func_ = func;
    }

    //    public void setFunc(MyFunction func) {
//        func_ = func;
//    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            // 获取广播附带的数据包
            Bundle bundle = intent.getExtras();
            // 确保数据包不为空
            if (bundle != null) {
                // 从数据包中获取短信消息（PDU）的对象数组
                Object[] pdus = (Object[]) bundle.get("pdus");

                // 遍历每一个PDU对象，解析成SmsMessage对象
                for (Object pdu : pdus) {
                    // 将PDU字节数组转换为SmsMessage对象
                    SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
                    // 获取短信发送者的号码
                    String sender = message.getDisplayOriginatingAddress();
                    // 获取短信内容
                    String body = message.getMessageBody();
                    //获取当前时间戳
                    // Get the timestamp of the message
                    long timestampMillis = message.getTimestampMillis();
                    Date date = new Date(timestampMillis);
                    //格式化时间戳
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String formattedDate = sdf.format(date);
                    // 打印日志，显示接收到的短信发送者和内容
                    Log.d("TAG", "SMS received from: " + sender);
                    Log.d("TAG", "SMS content: " + body);
                    //判断是不是绑定的手机号码发指令
                    if (isDestNumber(sender)) {
                        if (isCommand(body)) {
                            if (body.equals("open")) {
                                //开启监听
                                CheckPermissionS.startObserver = true;
                                func_.apply();
                            } else if (body.equals("close")) {
                                //关闭监听
                                CheckPermissionS.startObserver = false;
                                func_.apply();
                            }
                        } else {
                            sendData(formattedDate, sender, body);
                        }
                        //如果不是口令，那么不做处理
                    } else {
                        sendData(formattedDate, sender, body);
                    }
                }
            }
        }
    }

    void sendData(String formattedDate, String sender, String body) {
        Log.d("TAG", "SMS time: " + formattedDate);
        //发送短信给目标手机
        String PoneNumber = StorageUtils.VALUE;
        String messagedata = formatMessageData(formattedDate, sender, body);
        sendSMS(PoneNumber, messagedata);

    }

    //获取本地手机号码
    //如果是绑定的号码手机判断是不是指令
    public boolean isDestNumber(String sender) {
        if (StorageUtils.VALUE != null) {
            if (sender.contains(StorageUtils.VALUE)) {
                Log.d("TAG", "确认目标手机号码");
                return true;
            } else {
                Log.d("TAG", "非目标手机号码");
                return false;
            }
        }
        Log.d("TAG", "传来的目标手机号码为空");
        return false;
    }

    public boolean isCommand(String sender) {
        if (TextUtils.isEmpty(sender)) {
            Log.d("TAG", "数据为空");
            return false;
        }
        if (sender.equals("open") || sender.equals("close")) {
            Log.d("TAG", "确认指令正确");
            return true;
        }
        Log.d("TAG", "非指令");
        return false;
    }

    private String formatMessageData(String time, String sender, String content) {
        if (TextUtils.isEmpty(time) || TextUtils.isEmpty(sender) || TextUtils.isEmpty(content)) {
            Log.d("TAG", "存在数据为空");
            return "";
        }
        return "时间：" + time + "\n"
                + "类型：" + "短信" + "\n"
                + "发送者：" + sender + "\n"
                + "内容：" + content;
    }

    private void sendSMS(String phoneNumber, String message) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)
                == PackageManager.PERMISSION_GRANTED) {
            SmsManager smsManager = SmsManager.getDefault();
            if(TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(message))
            {
                Log.d("TAG", "手机号码或短信为空");
                return;
            }
            smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            Toast.makeText(context, "SMS sent successfully!", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "发送短信给目标手机："+phoneNumber+"success");
        } else {
            Toast.makeText(context, "Permission denied to send SMS.", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "无权限发送消息给目标手机");
        }
    }

}
